package com.cssy.xxkj.logic.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.byd.acegiext.domain.User;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.contants.BillTypeConstant;
import com.cssy.xxkj.logic.dao.LogicProductionDispatchingDAO;
import com.cssy.xxkj.logic.dao.LogicProductionDispatchingItemDAO;
import com.cssy.xxkj.logic.dao.LogicProductionReworkDAO;
import com.cssy.xxkj.logic.dao.LogicProductionReworkItemDAO;
import com.cssy.xxkj.logic.dao.SystemLogDAO;
import com.cssy.xxkj.logic.entity.LogicProductionDispatchingDO;
import com.cssy.xxkj.logic.entity.LogicProductionDispatchingItemDO;
import com.cssy.xxkj.logic.entity.LogicProductionReworkDO;
import com.cssy.xxkj.logic.entity.LogicProductionReworkItemDO;
import com.cssy.xxkj.logic.service.ILogicProductionReworkService;
import com.cssy.yd.logic.util.MathUtil;
import com.plat.exception.SyBaseException;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.IDCodeTypeUtil;
import com.plat.util.SessionUtil;
import com.yuendong.sy.po.code.SyCode;
import com.yuendong.sy.service.code.impl.SyCodeService;
/**
 * 生产派工业务方法
 * @modify hf 
 *
 */
@Service("logicProductionReworkService")
public class LogicProductionReworkServiceImpl implements ILogicProductionReworkService {
	private static final Logger logger = Logger.getLogger(LogicProductionReworkServiceImpl.class);
	@Resource(name = "logicProductionReworkDAO")
	private LogicProductionReworkDAO logicProductionReworkDAO;
	
	@Resource(name = "logicProductionDispatchingDAO")
	private LogicProductionDispatchingDAO logicProductionDispatchingDAO;
	
	@Resource(name = "logicProductionDispatchingItemDAO")
	private LogicProductionDispatchingItemDAO logicProductionDispatchingItemDAO;
	
	@Resource(name = "logicProductionReworkItemDAO")
	private LogicProductionReworkItemDAO  logicProductionReworkItemDAO;
	
	@Resource(name = "systemLogDAO")
	private SystemLogDAO systemLogDAO;
	
	@Resource(name = "syCodeService")
	private SyCodeService syCodeService;
	
	@Override
	public SearchResult findListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs=new SearchResult(scs);
		List<LogicProductionReworkDO>  list=logicProductionReworkDAO.find(scs);
		rs.setRecordCount(logicProductionReworkDAO.count(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public Integer delete(String id, User user) throws SyBaseException {
		logicProductionReworkDAO.deleteLogicProductionReworkDOByPrimaryKey(id);
		return null;
	}

	@Override
	public Integer update(LogicProductionReworkDO t, User user) throws SyBaseException {
		t.setBizModifyName(user.getName());
		t.setBizModifyDate(new Date());
		t.setBizVersionMark(t.getBizVersion());
		t.setBizVersion(t.getBizVersion()+1);
		return logicProductionReworkDAO.updateLogicProductionReworkDO(t);
	}

	@Override
	public LogicProductionReworkDO save(LogicProductionReworkDO sodo, User user) throws SyBaseException {
		sodo.setBizCreatorName(user.getName());
		sodo.setBizCreatorDate(new Date());
		sodo.setBizVersion(1);
		logicProductionReworkDAO.insertLogicProductionReworkDO(sodo);
		return sodo;
	}

	@Override
	public LogicProductionReworkDO findListById(String id) throws SyBaseException {
		return logicProductionReworkDAO.findLogicProductionReworkDOByPrimaryKey(id);
	}


	@Override
	public Integer deleteBizRemoved(String id) throws SyBaseException {
		return logicProductionReworkDAO.deleteBizRemoved(id);
	}

	

	@Override
	public List<LogicProductionReworkItemDO> findDispatItemList(String id) throws SyBaseException {
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty(null);
		scs.addCondition("zd001ProReworkId", id, SearchCondition.OP_EQUAL);
		List<LogicProductionReworkItemDO>  list=logicProductionReworkItemDAO.find(scs);
		return list;
	}

	@Override
	public void dispatSave(HttpServletRequest request, LogicProductionReworkDO curAP)
			throws SyBaseException {
		try {
			String itemdata = request.getParameter("itemdata");//物品数据
			String paramflag =request.getParameter("paramflag");
			
			curAP.setZd008Billstatus(paramflag);//单据状态
			List<LogicProductionReworkItemDO> Itemlist = JSONArray.parseArray(itemdata,LogicProductionReworkItemDO.class);
			User user = SessionUtil.getUser(request);
			if (StringUtils.isBlank(curAP.getId())) {
					String id = IDCodeTypeUtil.getId();
					curAP.setId(id);
					curAP.setZd001FormCode(syCodeService.getCode(BillTypeConstant.PROREWORK,BillTypeConstant.PROREWORK,SyCode.DATE_YYMM,5));
					this.save(curAP,user);
					for (LogicProductionReworkItemDO ItemDO : Itemlist) {
						ItemDO.setZd001ProReworkId(id);
						ItemDO.setId(IDCodeTypeUtil.getId());
						logicProductionReworkItemDAO.insertLogicProductionReworkItemDO(ItemDO);
					}
					logger.info("新增生产返工单成功");
			} else {
					int rs=this.update(curAP, user);
					if(0==rs){
						throw new SyBaseException("您操作的单据数据发生了改变!请您重新打开编辑！");
					}
					if(Itemlist!=null&&!Itemlist.isEmpty()&&Itemlist.size()>0){
						logicProductionReworkItemDAO.deleteDispatId(curAP.getId());
						List<LogicProductionReworkItemDO> list = this.findByIdItem(curAP,true);
						for(int i=0;i<Itemlist.size();i++){
							if(this.validateSubmit(list, Itemlist.get(i))){
								throw new SyBaseException("订单工序返工总数量大于派工数量，不合法！");
							}
							Itemlist.get(i).setZd001ProReworkId(curAP.getId());
							Itemlist.get(i).setId(IDCodeTypeUtil.getId());
							logicProductionReworkItemDAO.insertLogicProductionReworkItemDO(Itemlist.get(i));
						}
					}
					logger.info("修改生产返工单成功");
			}
			if(curAP.getZd008Billstatus().equals(BillStatusUtil.PROREWORK_BILL_STATUS_TWO)){
				LogicProductionDispatchingDO dispatch = new LogicProductionDispatchingDO();
				dispatch.setZd001FormCode(curAP.getZd002OriCode());
				List<LogicProductionDispatchingDO> planlist=logicProductionDispatchingDAO.findListByExample(dispatch);
				if(planlist!=null&&!planlist.isEmpty()&&planlist.size()>0){
					if(this.validateReturn(this.findByIdItem(curAP,false), planlist.get(0).getId())){
						planlist.get(0).setZd010ReworkStauts(2l);
					}else{
						planlist.get(0).setZd010ReworkStauts(1l);
					}
					planlist.get(0).setBizVersionMark(planlist.get(0).getBizVersion());
					planlist.get(0).setBizVersion(planlist.get(0).getBizVersion()+1);
					int lp=logicProductionDispatchingDAO.updateLogicProductionDispatchingDO(planlist.get(0));
					if(lp==0){
						throw new SyBaseException("您操作的原始单据数据发生了改变!请您重新打开编辑！");
					}
					logger.info("更新生产派工单状态成功");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error("操作生产返工单失败！");
			throw new SyBaseException(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
	}
	
	/**
	 * 验证返工数量是否合法
	 * @param list
	 * @param ItemDO
	 * @return
	 */
	private boolean validateSubmit(List<LogicProductionReworkItemDO> list,LogicProductionReworkItemDO ItemDO){
		BigDecimal bg = MathUtil.mathUtil.subtract(ItemDO.getZd030PlanQuantity(),ItemDO.getZd013Quantity());
		if(list!=null&&!list.isEmpty()&&list.size()>0){
			for(int i=0;i<list.size();i++){
				if(ItemDO.getZd029Process().equals(list.get(i).getZd029Process())){
					bg=MathUtil.mathUtil.subtract(bg, list.get(i).getZd013Quantity());
				}
			}
		}
		if(bg.compareTo(new BigDecimal(0))==-1){
			return true;
		}
		return false;
	}
	
	private List<LogicProductionReworkItemDO> findByIdItem(LogicProductionReworkDO curAP,boolean bl){
		List<LogicProductionReworkItemDO> list = new ArrayList<LogicProductionReworkItemDO>();
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty("removed");
		if(bl){
			scs.addCondition("zd001FormCode", curAP.getZd001FormCode(), SearchCondition.OP_NOTEQUAL);
		}
		scs.addCondition("zd002OriCode", curAP.getZd002OriCode(), SearchCondition.OP_EQUAL);
		scs.addCondition("zd008Billstatus", BillStatusUtil.PROREWORK_BILL_STATUS_TWO, SearchCondition.OP_EQUAL);
		List<LogicProductionReworkDO> result = this.findListByExample(scs).getResults();
		if(result!=null&&!result.isEmpty()&&result.size()>0){
			for(int i=0;i<result.size();i++){
				List<LogicProductionReworkItemDO> dispatItem = this.findDispatItemList(result.get(i).getId());
				list.addAll(dispatItem);
			}
		}
		return list;
	}
	
	/**
	 * 验证是否已经全部返工完成
	 * @param list
	 * @param planId
	 * @return
	 */
	private boolean validateReturn(List<LogicProductionReworkItemDO> list,String getId){
		LogicProductionDispatchingItemDO getitem = new LogicProductionDispatchingItemDO();
		getitem.setZd001ProDispatId(getId);
		List<LogicProductionDispatchingItemDO> getitemlist=logicProductionDispatchingItemDAO.findListByExample(getitem);
		boolean bl =true;//是否全部使用完成
		for(int n=0;n<getitemlist.size();n++){
			/*BigDecimal bd = getitemlist.get(n).getZd013Quantity();
			for(int i=0;i<list.size();i++){
				if(getitemlist.get(n).getZd029Process().equals(list.get(i).getZd029Process())){
					bd=MathUtil.mathUtil.subtract(bd, list.get(i).getZd013Quantity());	
				}
			}
			if(bd.compareTo(new BigDecimal(0))==1){
				bl=false;
			}*/
		}
		return bl;
	}
}
